// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.Diagnostics;
using System.Threading;

namespace Matrix.Common.Core.Watchdogs
{
    /// <summary>
    /// The watchdog will follow the lifespan of the application; and if activated 
    /// and the application starts the closing procedure, but fails to close in the
    /// given time frame, the watchdog will kill its own application.
    /// </summary>
    public static class SeppukuWatchdog
    {
        static object _syncRoot = new object();
        static DateTime _closeStarted = DateTime.MaxValue;

        static System.Timers.Timer _watchTimer = null;

        static TimeSpan _postCloseTimeout = TimeSpan.FromSeconds(25);
        
        /// <summary>
        /// What is the timeout to wait for, after starting the close process, before killing ourselves.
        /// </summary>
        public static TimeSpan PostCloseTimeout
        {
            get { return SeppukuWatchdog._postCloseTimeout; }
            set { SeppukuWatchdog._postCloseTimeout = value; }
        }

        /// <summary>
        /// Activate the watchdog, with the current settings.
        /// </summary>
        public static void Activate()
        {
            lock (_syncRoot)
            {
                if (_watchTimer == null)
                {
                    _watchTimer = new System.Timers.Timer(1000);
                    _watchTimer.Elapsed += new ElapsedEventHandler(_watchTimer_Elapsed);
                    _watchTimer.Start();
                }
            }
        }

        static void _watchTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (ApplicationLifetimeHelper.ApplicationClosing == false)
            {
                return;
            }

            lock (_syncRoot)
            {
                if (_closeStarted == DateTime.MaxValue)
                {
                    _closeStarted = DateTime.Now;
                }
                else if (DateTime.Now - _closeStarted >= _postCloseTimeout)
                {// Time to die.
                    _watchTimer.Stop();
                    _watchTimer.Elapsed -= new ElapsedEventHandler(_watchTimer_Elapsed);

                    System.Diagnostics.Trace.TraceWarning(string.Format("Process [{0}] performing suicide due to close timeout."), Process.GetCurrentProcess().ProcessName);
                    
                    Thread.Sleep(100);
                    Process.GetCurrentProcess().Kill();
                }
                
            }
        }
    }
}
